/**
 * 客户表单组合式函数
 * 提供客户表单的通用逻辑和状态管理
 */
import { ref, computed } from 'vue'
import type { Lead, LeadCreate, LeadUpdate } from '@/api/types'

export interface UseLeadFormOptions {
  initialData?: Partial<Lead>
  onSubmit?: (data: LeadCreate | LeadUpdate) => Promise<void>
  onCancel?: () => void
}

export function useLeadForm(options: UseLeadFormOptions = {}) {
  const { initialData, onSubmit, onCancel } = options

  // 表单数据
  const formData = ref<LeadCreate | LeadUpdate>({
    name: initialData?.name || '',
    phone: initialData?.phone || '',
    demand_type: initialData?.demand_type || 'rent_whole',
    budget_range: initialData?.budget_range || null,
    source_channel: initialData?.source_channel || 'other',
    stage: initialData?.stage || 'new',
    notes: initialData?.notes || null,
    owner_id: initialData?.owner_id || 1
  })

  // 表单验证规则
  const rules = computed(() => ({
    name: [
      { required: true, message: '请输入客户姓名', trigger: 'blur' },
      { min: 2, max: 50, message: '姓名长度应在2-50个字符之间', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    demand_type: [
      { required: true, message: '请选择需求类型', trigger: 'change' }
    ],
    source_channel: [
      { required: true, message: '请选择客户来源', trigger: 'change' }
    ],
    stage: [
      { required: true, message: '请选择客户阶段', trigger: 'change' }
    ],
    owner_id: [
      { required: true, message: '请选择负责人', trigger: 'change' }
    ]
  }))

  // 表单状态
  const loading = ref(false)
  const visible = ref(false)

  // 是否为编辑模式
  const isEdit = computed(() => !!(formData.value as LeadUpdate & { id?: number }).id)

  // 表单标题
  const title = computed(() => isEdit.value ? '编辑客户' : '新增客户')

  // 提交表单
  const handleSubmit = async () => {
    if (!onSubmit) return

    try {
      loading.value = true
      await onSubmit(formData.value)
      handleClose()
    } catch (error) {
      console.error('表单提交失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 取消表单
  const handleCancel = () => {
    if (onCancel) {
      onCancel()
    }
    handleClose()
  }

  // 关闭表单
  const handleClose = () => {
    visible.value = false
    resetForm()
  }

  // 重置表单
  const resetForm = () => {
    formData.value = {
      name: '',
      phone: '',
      demand_type: 'rent_whole',
      budget_range: null,
      source_channel: 'other',
      stage: 'new',
      notes: null,
      owner_id: 1
    }
  }

  // 打开表单（新增）
  const openCreate = () => {
    resetForm()
    visible.value = true
  }

  // 打开表单（编辑）
  const openEdit = (data: Lead) => {
    formData.value = {
      name: data.name,
      phone: data.phone,
      demand_type: data.demand_type,
      budget_range: data.budget_range,
      source_channel: data.source_channel,
      stage: data.stage,
      notes: data.notes,
      owner_id: data.owner_id
    } as LeadUpdate & { id?: number }
    // 保存 id 用于判断编辑模式
    ;(formData.value as LeadUpdate & { id?: number }).id = data.id
    visible.value = true
  }

  return {
    // 状态
    formData,
    rules,
    loading,
    visible,
    isEdit,
    title,
    
    // 方法
    handleSubmit,
    handleCancel,
    handleClose,
    resetForm,
    openCreate,
    openEdit
  }
}
